/**
 * 切换元素进入全屏/退出全屏
 * @param {HTMLElement} el
 */
export function elToggleFullScreen(el = document.documentElement) {
  if (!document.fullscreenElement) {
    el.requestFullscreen().catch((err) => {
      console.error(
        `Error attempting to enable full-screen mode: ${err.message} (${err.name})`
      );
    });
  } else {
    document.exitFullscreen();
  }
}

/**
 * 获取 CSS 变量
 * @param {string} name
 * @param {HTMLElement} el
 * @returns {string}
 */
export function getCSSVar(name, el = document.documentElement) {
  const _var = name.startsWith("--") ? name : `--${name}`;
  return getComputedStyle(el).getPropertyValue(_var).trim();
}

/**
 * 设置 CSS 变量
 * @param {*} name
 * @param {*} value
 * @param {*} el
 */
export function setCSSVar(name, value, el = document.documentElement) {
  const _var = name.startsWith("--") ? name : `--${name}`;
  el.style.setProperty(_var, value);
}

/**
 * 复制文本到剪贴板
 */
export const copyText = (() => {
  if (navigator.clipboard) {
    return (text, cb) => {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          cb && cb(true);
        })
        .catch((err) => {
          console.error(err);
          cb && cb(false);
        });
    };
  } else {
    return (text, cb) => {
      const input = document.createElement("input");
      input.value = text;
      document.body.appendChild(input);
      input.select();
      try {
        document.execCommand("copy");
        cb && cb(true);
      } catch (err) {
        console.error(err);
        cb && cb(false);
      } finally {
        document.body.removeChild(input);
      }
    };
  }
})();
